// Copyright 2024 Administrator
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// draggable.js
import { Directive, DirectiveBinding } from "vue";
export const draggable: Directive = {
  mounted(el: HTMLElement, binding: DirectiveBinding) {
    const startPosition = { x: 0, y: 0 };
    const dialogPosition = { x: 0, y: 0 };
    let dragging = false;

    const handleMouseDown = (e: any) => {
      startPosition.x = e.clientX;
      startPosition.y = e.clientY;
      dialogPosition.x = parseInt(el.style.left, 10) || 0;
      dialogPosition.y = parseInt(el.style.top, 10) || 0;

      document.addEventListener("mousemove", handleMouseMove);
      document.addEventListener("mouseup", handleMouseUp);

      dragging = true;

      e.stopPropagation();
      e.preventDefault();
    };

    const handleMouseMove = (e: any) => {
      if (dragging) {
        const offsetX = e.clientX - startPosition.x;
        const offsetY = e.clientY - startPosition.y;
        el.style.left = `${dialogPosition.x + offsetX}px`;
        el.style.top = `${dialogPosition.y + offsetY}px`;
      }
    };

    const handleMouseUp = () => {
      document.removeEventListener("mousemove", handleMouseMove);
      document.removeEventListener("mouseup", handleMouseUp);

      dragging = false;
    };

    el.addEventListener("mousedown", handleMouseDown);
  },
};
